﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using java.sql;
using lineage2.commons.dbutils;
using org.slf4j;

namespace Game.dao
{
    public class ClanDataDAO
{
	/**
	 * Field _log.
	 */
	private static Logger _log = LoggerFactory.getLogger(typeof (ClanDataDAO));
	/**
	 * Field _instance.
	 */
	private static ClanDataDAO _instance = new ClanDataDAO();
	/**
	 * Field SELECT_CASTLE_OWNER. (value is ""SELECT clan_id FROM clan_data WHERE hasCastle = ? LIMIT 1"")
	 */
	public static String SELECT_CASTLE_OWNER = "SELECT clan_id FROM clan_data WHERE hasCastle = ? LIMIT 1";
	/**
	 * Field SELECT_FORTRESS_OWNER. (value is ""SELECT clan_id FROM clan_data WHERE hasFortress = ? LIMIT 1"")
	 */
	public static String SELECT_FORTRESS_OWNER = "SELECT clan_id FROM clan_data WHERE hasFortress = ? LIMIT 1";
	/**
	 * Field SELECT_CLANHALL_OWNER. (value is ""SELECT clan_id FROM clan_data WHERE hasHideout = ? LIMIT 1"")
	 */
	public static String SELECT_CLANHALL_OWNER = "SELECT clan_id FROM clan_data WHERE hasHideout = ? LIMIT 1";
	
	/**
	 * Method getInstance.
	 * @return ClanDataDAO
	 */
	public static ClanDataDAO getInstance()
	{
		return _instance;
	}
	
	/**
	 * Method getOwner.
	 * @param c Castle
	 * @return Clan
	 */
	public Clan getOwner(Castle c)
	{
		return getOwner(c, SELECT_CASTLE_OWNER);
	}
	
	/**
	 * Method getOwner.
	 * @param f Fortress
	 * @return Clan
	 */
	public Clan getOwner(Fortress f)
	{
		return getOwner(f, SELECT_FORTRESS_OWNER);
	}
	
	/**
	 * Method getOwner.
	 * @param c ClanHall
	 * @return Clan
	 */
	public Clan getOwner(ClanHall c)
	{
		return getOwner(c, SELECT_CLANHALL_OWNER);
	}
	
	/**
	 * Method getOwner.
	 * @param residence Residence
	 * @param sql String
	 * @return Clan
	 */
	private Clan getOwner(Residence residence, String sql)
	{
		Connection con = null;
		PreparedStatement statement = null;
		ResultSet rset = null;
		try
		{
			con = DatabaseFactory.getInstance().getConnection();
			statement = con.prepareStatement(sql);
			statement.setInt(1, residence.getId());
			rset = statement.executeQuery();
			if (rset.next())
			{
				return ClanTable.getInstance().getClan(rset.getInt("clan_id"));
			}
		}
		catch (Exception e)
		{
			_log.error("ClanDataDAO.getOwner(Residence, String)", e);
		}
		finally
		{
			DbUtils.closeQuietly(con, statement, rset);
		}
		return null;
	}
}

}
